package com.example.onlinemarket.graphics;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.example.onlinemarket.R;
import com.example.onlinemarket.model.Good;

import static com.example.onlinemarket.util.ActivityUtil.goShop;
import static com.example.onlinemarket.util.FileUtil.externalFilesDir;
import static com.example.onlinemarket.util.HttpUtil.addGoodToShoppingCart;

public class GoodInfoDialog extends AlertDialog {

    private ImageView goodImgIv;
    private TextView goodNameTv;
    private TextView goodDescribeTv;
    private TextView goodPriceTv;
    private TextView goShopBtn;
    private Button purchaseBtn;

    private Good good;
    private Context context;

    protected GoodInfoDialog(@NonNull Context context, Good good) {
        super(context);
        this.context = context;
        this.good = good;
    }

    public static GoodInfoDialog newInstance(@NonNull Context context, Good good) {
        GoodInfoDialog dialog = new GoodInfoDialog(context, good);
        dialog.create();
        dialog.setCancelable(true);
        return dialog;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_good_info);
        //初始化组件
        initWidgets();
        //设置事件监听器
        setWidgetsListener();
    }

    //设置事件监听器
    private void setWidgetsListener() {
        goShopBtn.setOnClickListener(v -> {
            dismiss();
            new Thread(() -> goShop((Activity) context, good.getUserId())).start();
        });
        purchaseBtn.setOnClickListener(v -> {
            dismiss();
            addGoodToShoppingCart(good.getGoodId());
        });
    }

    //初始化组件
    private void initWidgets() {
        goodImgIv = findViewById(R.id.tv_good_info_good_img);
        goodNameTv = findViewById(R.id.tv_good_info_good_name);
        goodPriceTv = findViewById(R.id.tv_good_info_good_price);
        goodDescribeTv = findViewById(R.id.tv_good_info_good_describe);
        goShopBtn = findViewById(R.id.tv_good_info_shop);
        purchaseBtn = findViewById(R.id.btn_good_info_add_shoppingcart);
        Glide.with(context).load(externalFilesDir+good.getImgPath()).override(350,350).placeholder(R.drawable.ic_no_img).into(goodImgIv);
        goodNameTv.setText(good.getGoodName());
        goodDescribeTv.setText(good.getDescription());
        goodPriceTv.setText(String.valueOf(good.getSellPrice()));
    }
}
